package com.wcl.nullmusic.ui.fragment;

import android.os.AsyncTask;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.android.volley.Response;
import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader;
import com.google.gson.Gson;
import com.wcl.nullmusic.R;
import com.wcl.nullmusic.base.BaseFragment;
import com.wcl.nullmusic.mode.RecommendResult;
import com.wcl.nullmusic.mode.Recommend_CategoryContents;
import com.wcl.nullmusic.mode.Recommend_CategoryContents_List;
import com.wcl.nullmusic.mode.Recommend_FocusImages_List;
import com.wcl.nullmusic.mode.db.NullMusic_DBTools;
import com.wcl.nullmusic.ui.adapter.RecommendRecyclerViewAdapter;
import com.wcl.nullmusic.ui.adapter.RecommendViewPagerAdapter;
import com.wcl.nullmusic.utils.Contant;
import com.wcl.nullmusic.utils.FixedSpeedScroller;
import com.wcl.nullmusic.utils.ImageHandler;
import com.wcl.nullmusic.utils.NetworkUtils;
import com.wcl.nullmusic.utils.VolleyUtils;

import com.wcl.nullmusic.view.effect.RotateTransformer;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.List;

/**
 * Created by dllo on 16/1/5.
 */
public class RecommendFragment extends BaseFragment implements ViewPager.OnPageChangeListener {
    public ImageHandler handler = new ImageHandler(new WeakReference<RecommendFragment>(this));
    public ViewPager viewPager;
    private RecyclerView recyclerView;
    private RecyclerViewHeader header;
    private RecommendRecyclerViewAdapter recyclerViewAdapter;
    private RecommendViewPagerAdapter viewPagerAdapter;
    private int viewpagerSize = 7;
    private ImageView[] imageViews = new ImageView[viewpagerSize];
    private LinearLayout recommend_dots;
    private FixedSpeedScroller mScroller = null;
    private NullMusic_DBTools dbTools;


    @Override
    protected int getLayout() {
        return R.layout.fragment_recommend;
    }

    @Override
    protected void getVaule() {

    }

    @Override
    protected void initView(View view) {
        viewPager = (ViewPager) view.findViewById(R.id.recommend_viewPager);
        recyclerView = (RecyclerView) view.findViewById(R.id.recommend_recyclerView);
        header = (RecyclerViewHeader) view.findViewById(R.id.recommend_recyclerViewHeader);
        recyclerViewAdapter = new RecommendRecyclerViewAdapter(getActivity());
        viewPagerAdapter = new RecommendViewPagerAdapter(getActivity());
        recommend_dots = (LinearLayout) view.findViewById(R.id.recommend_dots);
        dbTools = new NullMusic_DBTools(getActivity());

    }

    @Override
    protected void initData() {
        initDots();
        //   recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(recyclerViewAdapter);
        header.attachTo(recyclerView, true);
        viewPager.setPageTransformer(true, new RotateTransformer());
        viewPager.setAdapter(viewPagerAdapter);
        loadData();
        controlViewPagerSpeed();
        //  viewPager.setCurrentItem(Integer.MAX_VALUE / 2);
        handler.sendEmptyMessageDelayed(ImageHandler.MSG_BREAK_SILENT, ImageHandler.MSG_DELAY);
    }

    @Override
    protected void listener() {
        viewPager.addOnPageChangeListener(this);
    }

    private void loadData() {
        if (NetworkUtils.isConnected())
            VolleyUtils.getInstance().StringRequest(Contant.RECOMMEND_RECYCLERVIEW_URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Gson gson = new Gson();
                    RecommendResult result = gson.fromJson(response, RecommendResult.class);
                    recommend_categoryContents_lists = result.getCategoryContents().getList();
                    recommend_focusImages_lists = result.getFocusImages().getList();
                    recyclerViewAdapter.addData(recommend_categoryContents_lists);
                    viewPagerAdapter.addData(recommend_focusImages_lists);
                    viewPager.setCurrentItem(97);
                    saveData(recommend_categoryContents_lists, recommend_focusImages_lists);
                }
            }, "Recommend_RecyclerView_StringRequest");
        else {
            QueryData queryData = new QueryData();
            queryData.execute();
        }
    }

    private void initDots() {
        for (int i = 0; i < viewpagerSize; i++) {
            ImageView imageView = new ImageView(getActivity());
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(15, 15);
            layoutParams.setMargins(10, 0, 10, 0);
            imageView.setLayoutParams(layoutParams);

            imageViews[i] = imageView;
            if (i == 0)
                imageViews[i].setImageResource(R.mipmap.test_greenicon);
            else
                imageViews[i].setImageResource(R.mipmap.test_grayicon);
            recommend_dots.addView(imageViews[i]);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//        Log.i("qwe", "onPageScrolled");

    }

    @Override
    public void onPageSelected(int position) {

        handler.sendMessage(Message.obtain(handler, ImageHandler.MSG_PAGE_CHANGED, position, 0));
        int currentPosition = position % viewpagerSize;
        imageViews[currentPosition].setImageResource(R.mipmap.test_greenicon);

        for (int i = 0; i < viewpagerSize; i++) {
            if (currentPosition == i)
                imageViews[currentPosition].setImageResource(R.mipmap.test_greenicon);
            else
                imageViews[i].setImageResource(R.mipmap.test_grayicon);
        }


    }

    // 实现轮播效果的暂停和恢复
    @Override
    public void onPageScrollStateChanged(int state) {
        switch (state) {
            case ViewPager.SCROLL_STATE_DRAGGING:
                handler.sendEmptyMessage(ImageHandler.MSG_KEEP_SILENT);
                break;
            case ViewPager.SCROLL_STATE_IDLE:
                handler.sendEmptyMessageDelayed(ImageHandler.MSG_UPDATE_IMAGE, ImageHandler.MSG_DELAY);
                break;
            default:
                break;
        }
    }

    // viewPager 轮播速度控制器
    private void controlViewPagerSpeed() {
        try {
            Field mField;

            mField = ViewPager.class.getDeclaredField("mScroller");
            mField.setAccessible(true);

            mScroller = new FixedSpeedScroller(
                    viewPager.getContext(),
                    new AccelerateInterpolator());
            mScroller.setmDuration(500); // 2000ms
            mField.set(viewPager, mScroller);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveData(final List<Recommend_CategoryContents_List> datas, final List<Recommend_FocusImages_List> viewpagerDatas) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                dbTools.updateAll_Recommend_Recyclerview_List(datas);
                dbTools.updateAll_Recommend_Recommend_Viewpager(viewpagerDatas);
            }
        }).start();
    }

    private void queryData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<Recommend_CategoryContents_List> contents_lists = dbTools.queryAll_Recommend_Recyclerview_List();
                for (Recommend_CategoryContents_List contents_list : contents_lists) {
                    contents_list.setList(dbTools.queryPostion_Recommend_Recyclerview_List_List(contents_list.getPosition()));
                }
                List<Recommend_FocusImages_List> focusImages_lists = dbTools.queryAll_Recommend_Viewpager();
                recyclerViewAdapter.addData(contents_lists);
                viewPagerAdapter.addData(focusImages_lists);
            }
        }).start();
    }

    List<Recommend_FocusImages_List> recommend_focusImages_lists;
    List<Recommend_CategoryContents_List> recommend_categoryContents_lists;

    class QueryData extends AsyncTask<Void, Void, Void> {

        // 后台执行方法
        @Override
        protected Void doInBackground(Void... params) {

            recommend_categoryContents_lists = dbTools.queryAll_Recommend_Recyclerview_List();
            for (Recommend_CategoryContents_List contents_list : recommend_categoryContents_lists) {
                contents_list.setList(dbTools.queryPostion_Recommend_Recyclerview_List_List(contents_list.getPosition()));
            }
            recommend_focusImages_lists = dbTools.queryAll_Recommend_Viewpager();

            return null;
        }


        // 在执行后台任务之前调用,可以进行友好提示
        @Override
        protected void onPreExecute() {
            Toast.makeText(getActivity(), "Recommend正在加载数据", Toast.LENGTH_SHORT).show();

        }

        @Override
        protected void onPostExecute(Void aVoid) {

            recyclerViewAdapter.addData(recommend_categoryContents_lists);
            viewPagerAdapter.addData(recommend_focusImages_lists);
            viewPager.setCurrentItem(97);
            Toast.makeText(getActivity(), "Recommend数据加载完成", Toast.LENGTH_SHORT).show();
        }
    }
}